var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/test'); 

var db = mongoose.connection;
db.once('open', function(err){
    console.log("数据库成功打开！");
});

var studentSchema = new mongoose.Schema({       // 学生
    "name" : String,
    "age" : Number,
    "sex" : String
});
var sessionSchema = new mongoose.Schema({      // 课程
    "name" : String,
    "info" : String,
    "student" : [studentSchema]
});

studentSchema.methods.Addage = function(){  // 实例方法，增岁
    this.age++;
    this.save();
}
sessionSchema.methods.AddStudent = function(studentObj,callback){   // 添加学生
    this.student.push(studentObj);
    this.save(function(){
        callback();
    });
}

sessionSchema.methods.FindStudent = function(num,callback){ // 寻找学生，维护两个列表数据同步
    Student.findOne({"name":this.student[num].name},function(err,result){
        callback(err,result);
    });
}

var Student = mongoose.model("Student",studentSchema)
var Session = mongoose.model("Session",sessionSchema);

// var xiaoming = new Student({"name":"小明","age":20,"sex":"男"});
// xiaoming.save();
// var mathh = new Session({
//     "name" : "数学课",
//     "info" : "学数学的"
// });
// mathh.AddStudent(xiaoming,function(){
//     console.log("添加成功！");
// })

// Student.findOne({"name":"小明"},function(err,student){     // 通过姓名寻找
//     student.Addage();
// });

Session.findOne({"name":"数学课"},function(err,sess){   // 通过课程找学生
    sess.FindStudent(0,function(err,result){
        console.log(result);
    });
});